package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class RecursiveAddToZip {
	public static void recursiveAddToZip(File source, File zipFile,
	                                     String pathInZip) throws IOException {
		recursiveAddToZip(new File[]{source}, zipFile, pathInZip);
	}

	public static void recursiveAddToZip(File[] files, File zipFile,
	                                     String pathInZip) throws IOException {
		FileOutputStream fOut = null;
		ZipOutputStream zipOut = null;

		try {
			fOut = new FileOutputStream(zipFile);
			zipOut = new ZipOutputStream(fOut);

			for (File f : files) {
				recursiveAddToZip(f, zipOut, pathInZip);
			}
		} finally {
			if (zipOut != null)
				zipOut.close();
			else if (fOut != null)
				fOut.close();
		}
	}

	private static void recursiveAddToZip(File source,
	                                      ZipOutputStream zipOut, String pathInZip) throws IOException {
		if (source.isDirectory()) {
			if (pathInZip.equals(""))
				pathInZip = source.getName();
			else
				pathInZip = pathInZip + "/" + source.getName();
			for (File f : source.listFiles()) {
				recursiveAddToZip(f, zipOut, pathInZip);
			}
		} else if (source.isFile()) {
			addToZip(zipOut, source, pathInZip);
		}
	}

	public static void addToZip(File zipFile, File source, String pathInZip)
			throws IOException {
		addToZip(zipFile, new File[]{source}, pathInZip);
	}


	public static void addToZip(File zipFile, File[] files, String pathInZip)
			throws IOException {
		FileOutputStream fOut = null;
		ZipOutputStream zipOut = null;

		try {
			fOut = new FileOutputStream(zipFile);
			zipOut = new ZipOutputStream(fOut);

			for (File f : files) {
				addToZip(zipOut, f, pathInZip);
			}
		} finally {
			if (zipOut != null)
				zipOut.close();
			else if (fOut != null)
				fOut.close();
		}
	}

	private static void addToZip(ZipOutputStream zipOut, File source,
	                             String pathInZip) throws IOException {
		BufferedOutputStream out = null;

		FileInputStream fIn = null;
		BufferedInputStream in = null;

		final int bufSize = 512;
		try {
			fIn = new FileInputStream(source);
			in = new BufferedInputStream(fIn, bufSize);

			String filePathInZip = pathInZip + "/" + source.getName();
			if (pathInZip.equals(""))
				filePathInZip = source.getName();

			ZipEntry entry = new ZipEntry(filePathInZip);
			zipOut.putNextEntry(entry);

			out = new BufferedOutputStream(zipOut, bufSize);

			int count = 0;
			byte[] buffer = new byte[bufSize];
			while ((count = in.read(buffer, 0, buffer.length)) > -1) {
				out.write(buffer, 0, count);
			}
			out.flush();
			zipOut.closeEntry();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				in.close();
			else if (fIn != null)
				fIn.close();
		}
	}
}
